<template>
  <div>
    <div>
      <FormEdit :data-form="formData0" />
    </div>
    <div class="checked-device">
      <div class="checked-device-title"><span>点检设备</span></div>
      <h-table-list
        border
        type="local"
        :data="tableData"
        :show-pagination="false"
        :columns="columns"
      >
        <!-- <ListOpearteButton /> -->
        <el-button @click="addCheckedDevice">添加点检设备</el-button>
        <span>只可选择台账状态【启用】的设备，提交审批后不可更改</span>
        <!-- <template
          slot="preview-column"
          slot-scope="scope"
        >
          <p>{{ scope.row.status }}</p>
        </template> -->

        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <!-- <el-button>上传保养部位简图</el-button> -->
          <el-button
            size="mini"
            @click="deleteDeviceData(scope.$index)"
          >删除</el-button>

        </template>
      </h-table-list>
    </div>
    <div class="checked-device">
      <div class="checked-device-title"><span>点检项</span></div>
      <el-button @click="addCheckedItems">添加点检项</el-button>
      <el-button @click="addCheckedNocontentItem">添加空白点检项</el-button>
      <el-form
        ref="productRuleForm"
        :model="productRuleForm"
        :rules="productRuleForm.rules"
        :show-message="false"
      >
        <h-table-list
          border
          type="local"
          :data="productRuleForm.tableData"
          :show-pagination="false"
          :columns="column2s"
        >
          <!--用插槽templete占位替换自定义部分 -->
          <template
            slot="operate-part"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.part'"
              :rules="productRuleForm.rules.part"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].part" />
            </el-form-item>
          </template>
          <template
            slot="operate-content"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.content'"
              :rules="productRuleForm.rules.content"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].content" />
            </el-form-item>
          </template>
          <template
            slot="operate-standard"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.standard'"
              :rules="productRuleForm.rules.standard"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].standard" />
            </el-form-item>
          </template>
          <template
            slot="operate-method"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.method'"
              :rules="productRuleForm.rules.method"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].method" />
            </el-form-item>
          </template>
          <template
            slot="operate-upPicFlag"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.upPicFlag'"
              :rules="productRuleForm.rules.upPicFlag"
            >
              <el-select v-model="productRuleForm['tableData'][scope.$index].upPicFlag">
                <el-option
                  :value="0"
                  :label="'不上传'"
                />
                <el-option
                  :value="1"
                  :label="'选填'"
                />
                <el-option
                  :value="2"
                  :label="'必填'"
                />
              </el-select>
            </el-form-item>
          </template>
          <template
            slot="operate-upVideoFlag"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.upVideoFlag'"
              :rules="productRuleForm.rules.upVideoFlag"
            >
              <el-select v-model="productRuleForm['tableData'][scope.$index].upVideoFlag">
                <el-option
                  :value="0"
                  :label="'不上传'"
                />
                <el-option
                  :value="1"
                  :label="'选填'"
                />
                <el-option
                  :value="2"
                  :label="'必填'"
                />
              </el-select>
            </el-form-item>
          </template>
          <template
            slot="operate-button"
            slot-scope="scope"
          >
            <el-button
              size="mini"
              @click="moveProTableData(scope.$index, scope.$index - 1)"
            >上移</el-button>
            <el-button
              size="mini"
              @click="moveProTableData(scope.$index, scope.$index + 1)"
            >下移</el-button>
            <el-button
              size="mini"
              @click="deleteProTableData(scope.$index)"
            >删除</el-button>
          </template>
        </h-table-list>
      </el-form>
    </div>

    <div>
      <FormEdit :data-form="operateForm0" />
    </div>
    <div class="check-device-buttons">
      <el-button
        type="primary"
        class="submit_btn"
        @click="() => submit(1)"
      >提交审批</el-button>
      <el-button
        v-if="state"
        type="primary"
        class="submit_btn"
        @click="() => submit(0)"
      >存草稿</el-button>
      <CacelButton />
    </div>
    <DownloadIdentify
      :visible.sync="dialogDeviceVisible"
      title="添加点检设备"
      @cancel="cancel"
      @update="addChooseDevices"
    >
      <h-table-list
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="deviceBasic.records"
        :columns="columns1s"
        :pagination-info="paginationInfo"
        :form-options="formOptions1s"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="preview-column"
          slot-scope="scope"
        >
          <p>{{ scope.row.status }}</p>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >

          <tableButton :row="scope.row" />

        </template>
      </h-table-list>
    </DownloadIdentify>
    <DownloadIdentify
      :visible.sync="dialogPartVisible"
      title="添加点检项目"
      @cancel="cancel2s"
      @update="addChooseItems"
    >
      <h-table-list
        ref="addCheckDeviceTable"
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="device_pointcheck_items.records"

        :columns="column3s"
        :pagination-info="paginationInfo2"
        :form-options="formOptions2s"
        @selection-change="handleSelectionItemsChange"
      >
        <template
          slot="preview-column"
          slot-scope="scope"
        >
          <p>{{ scope.row.status }}</p>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import FormEdit from '@/components/formEdit/index'
import ListOpearteButton from '@/components/AllButton/button2'
import DownloadIdentify from '@/components/FormDialog'
import CacelButton from '@/components/AllButton/cancel'
import data from './const'
import { uniComplexArr } from '@/utils'
export default {
  components: { FormEdit, ListOpearteButton, DownloadIdentify, CacelButton },

  data() {
    return {
      // 临时加个单据状态控制草稿按钮显隐藏
      state: '',
      // 点检项数据
      productRuleForm: {
        tableData: [
          // {
          //   part: "1", //点检部位
          //   content: "2", //点检内容
          //   standard: "21", //点检基准 非必须
          //   method: "21", //点检方法 非必须
          //   upPicFlag: 0, //上传图片 0不上传 1选填 2必填
          //   upVideoFlag: 0, //上传图片 0不上传 1选填 2必填
          // },
        ],
        rules: {
          part: [{ required: true, message: '请选择日期', trigger: 'blur' }],
          content: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          standard: [
            { required: true, message: '请输入电话号码', trigger: 'blur' }
          ],
          method: [{ required: true, message: '请输入地址', trigger: 'blur' }],
          upPicFlag: [
            { required: true, message: '请输入地址', trigger: 'blur' }
          ],
          upVideoFlag: [
            { required: true, message: '请输入地址', trigger: 'blur' }
          ]
        }
      },
      chooseDevices: [],
      chooseItems: [],
      formOptions1s: {
        inline: true,
        submitBtnText: '查询',
        showResetBtn: false,
        searchParamsHandler: () => {
          console.log('搜索')
          this.getDeviceList(
            Object.assign(this.$store.state.deviceBasic.listSearchParams, { state: 13 })
          )
        },
        changevalue: params => {
          console.log(params)
          this.$store.dispatch(
            'deviceBasic/setListSearchParams',
            params
          )
        },
        resetBtnCallback: () => {
          this.$store.dispatch(
            'device_pointcheck_items/setListSearchParams',
            {}
          )
          this.getList(

          )
        },
        forms: [
          { prop: 'deviceName', label: '设备名称' },

          { prop: 'assetNumber', label: '设备编号' },
          { prop: 'organId', label: '使用部门', itemType: 'cascader', options: this.$store.state.app.allCode.department }
          // {
          //   prop: "useDepartmentId",
          //   label: "归属部门",
          //   itemType: "select",
          //   options: [
          //     { value: "", label: "部门1" },
          //     { value: 0, label: "部门2" },
          //     { value: 1, label: "部门3" },
          //   ],
          // },

          // {
          //   prop: "positionsId",
          //   label: "职位",
          //   itemType: "select",
          //   options: [
          //     { value: 0, label: "通用" },
          //     { value: 1, label: "专用" },
          //   ],
          // },
          //  {
          //   prop: "userType",
          //   label: "账号类别",
          //   itemType: "select",
          //   options: [
          //     { value: "0", label: "手机" },
          //     { value: "1", label: "PC" },
          //   ],
          // },
        ]
      },

      formOptions2s: {
        inline: true,
        submitBtnText: '查询',
        showResetBtn: false,
        searchParamsHandler: () => {
          console.log('搜索')
          this.getItemsList(
            this.$store.state.device_pointcheck_items.listSearchParams
          )
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params)
          this.$store.dispatch(
            'device_pointcheck_items/setListSearchParams',
            params
          )
        },
        resetBtnCallback: () => {
          this.$store.dispatch(
            'device_pointcheck_items/setListSearchParams',
            {}
          )
          this.getList(
            this.$store.state.device_pointcheck_items.listSearchParams
          )
        },
        forms: [
          { prop: 'itemGroupId', label: '分组', itemType: 'select', options: [] },

          { prop: 'part', label: '点检部位' },
          { prop: 'content', label: '点检内容' }
          // {
          //   prop: "useDepartmentId",
          //   label: "归属部门",
          //   itemType: "select",
          //   options: [
          //     { value: "", label: "部门1" },
          //     { value: 0, label: "部门2" },
          //     { value: 1, label: "部门3" },
          //   ],
          // },

          // {
          //   prop: "positionsId",
          //   label: "职位",
          //   itemType: "select",
          //   options: [
          //     { value: 0, label: "通用" },
          //     { value: 1, label: "专用" },
          //   ],
          // },
          //  {
          //   prop: "userType",
          //   label: "账号类别",
          //   itemType: "select",
          //   options: [
          //     { value: "0", label: "手机" },
          //     { value: "1", label: "PC" },
          //   ],
          // },
        ]
      },
      dialogDeviceVisible: false,
      dialogPartVisible: false,
      paginationInfo: {
        sizeChange: e => {
          console.log(e)
        },
        currentChange: e => {
          //    debugger;
          this.$store.dispatch('deviceBasic/setListSearchParams', {
            current: e
          })
          this.getDeviceList(
            Object.assign({}, this.$store.state.deviceBasic.listSearchParams)
          )
        },
        current: 1,
        total: 10
      },
      paginationInfo2: {
        sizeChange: e => {
          console.log(e)
        },
        currentChange: e => {
          this.$store.dispatch('device_pointcheck_items/setListSearchParams', {
            current: e
          })
          this.getItemsList(
            Object.assign(
              {},
              this.$store.state.device_pointcheck_items.listSearchParams
            )
          )
        },
        current: 1,
        total: 10
      },
      tableData: [],
      tableData2s: [
        { id: 0, checkContent: '22' },
        { id: 1, checkContent: '22' },
        { id: 2, checkContent: '22' }
      ],
      tableData3s: [],
      data: this.deepCopy(data),
      formData0: this.deepCopy(data.basicForm0),
      operateForm0: this.deepCopy(data.operateForm0),
      columns: [
        { type: 'index', label: '序号', width: 140 },

        {
          prop: 'deviceName',
          label: '设备名称',
          width: 100
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: 'assetNumber',
          label: '设备编号',
          width: 100
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.deviceNumber ? deviceInfo.deviceNumber :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: 'organName', label: '使用部门', minWidth: 180 },
        // { prop: "departmentName", label: "点检部位简图", minWidth: 180 },   //暂时隐藏
        {
          prop: 'operate',
          label: '操作',
          minWidth: 180,
          slotName: 'operate-column'
          // fixed: "right"
        }
      ],
      columns1s: [
        { type: 'selection', label: '序号' },
        { prop: 'deviceName', label: '设备名称' },
        { prop: 'assetCode', label: '固定资产编码' },

        { prop: 'assetNumber', label: '设备编号' },
        { prop: 'deviceClass', label: '设备类别' },
        { prop: 'typeId', label: '设备分类' },
        {
          prop: 'organName',
          label: '使用部门'
        },

        { prop: 'responsible', label: '责任人' },
        { prop: 'deviceModel', label: '型号' }
      ],
      column2s: [
        { type: 'index', label: '序号', width: 100 },
        {
          prop: 'part',
          label: '点检部位',
          slotName: 'operate-part',
          width: 300
        },
        {
          prop: 'content',
          label: '点检内容',
          slotName: 'operate-content',
          width: 300
        },

        {
          prop: 'standard',
          label: '点检基准',
          slotName: 'operate-standard',
          width: 350
        },
        {
          prop: 'method',
          label: '点检方法',
          slotName: 'operate-method',
          width: 350
        },
        { prop: 'upPicFlag', label: '上传图片', slotName: 'operate-upPicFlag' },
        {
          prop: 'upVideoFlag',
          label: '上传视频',
          slotName: 'operate-upVideoFlag'
        },

        {
          prop: 'responsible',
          label: '操作',
          width: 350,
          slotName: 'operate-button'
        }
      ],
      column3s: [
        { type: 'selection', label: '序号' },

        { prop: 'itemGName', label: '分组' },

        {
          prop: 'part',
          label: '点检部位',
          width: 100
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: 'content',
          label: '点检内容',
          width: 100
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.content ? deviceInfo.content :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: 'standard', label: '点检基准', minWidth: 180 },
        { prop: 'method', label: '点检方法', minWidth: 180 },
        // {
        //   prop: "itemsSum",
        //   label: "点检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        {
          prop: 'upPicFlag',
          label: '上传图片',
          minWidth: 180,
          filter: 'formatIsNecessary'
        },
        {
          prop: 'upVideoFlag',
          label: '上传视频',
          minWidth: 180,
          filter: 'formatIsNecessary'
        }
        // {
        //   prop: "createdTime",
        //   label: "创建时间",
        //   minWidth: 180,
        // //  slotName: "createdTime",
        // },
      ]
    }
  },
  watch: {

    // 这里处理为数据监听改变form的配置来实现业务上的模板更换,后续考虑优化
    'formData0.0.formModel.planPeriodType': {
      handler: function(val) {
        console.log('深度监听', val)
        if (val == '0') {
          // 定期
          this.formData0[0].formComponent = this.deepCopy(data.basicForm0[0].formComponent.concat(data.basicForm0[0].formComponent2)) // this.deepCopy(data.basicForm0);

          console.log(this.formData0)
        } else if (val == '1') {
          // 日常
          this.formData0[0].formComponent = this.deepCopy(data.basicForm0[0].formComponent.concat(data.basicForm0[0].formComponent3)) // this.deepCopy(data.basicForm0);

          console.log(this.formData0)
        }
      },
      deep: true,
      immediate: true
    },
    'operateForm0.0.formModel.membType': {
      handler: function(val) {
        console.log('深度监听', val)
        if (val == '0') {
          // 指定人员
          this.operateForm0 = this.data.operateForm0
        } else if (val == '1') {
          // 指定部门
          this.operateForm0 = this.data.operateForm1
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapState(['deviceBasic', 'app', 'device_pointcheck_items', 'device_pointcheck_itemsGroup'])
  },
  mounted() {
    // 先判断有无数据，是新增还是编辑
    const { fullPath } = this.$route
    const id = localStorage.getItem(fullPath)
    if (id) {
      // 存在id时则请求拉取详情
      this.$store
        .dispatch('device_pointcheck_plan/requestEditInfo', id)
        .then(res => {
          this.state = res.data.state == 10
          const resInfo = JSON.parse(JSON.stringify(res.data))
          if (res.data.dailySkipDays) {
            resInfo.dailySkipDays = res.data.dailySkipDays.split(',')
          }

          console.log(res.data.dailyPeriodType, '+++aa')
          resInfo.dailyPeriodType = res.data.dailyPeriodType.toString()
          resInfo.planPeriodType = res.data.planPeriodType.toString()
          resInfo.membType = res.data.membType.toString()
          resInfo.userId = res.data.userId + ',' + res.data.userName

          // 四部分数值回填
          this.$set(this.formData0[0], 'formModel', resInfo)
          res.data.planRefDeviceList = res.data.planRefDeviceList.map(e => {
            e.organId = e.useOrganId
            e.organName = e.useOrganName
            return e
          })
          this.$set(this, 'tableData', res.data.planRefDeviceList)
          this.chooseDevices = res.data.planRefDeviceList
          this.$set(this.productRuleForm, 'tableData', res.data.planItemList)
          this.$set(this.operateForm0[0], 'formModel', resInfo)
          console.log(this, '-+-+-')
        })
        .catch(err => {})
    } else {
      this.state = true
    }

    // 加载点检设备和点检项
    this.getDeviceList({ state: 13 })
    this.getItemsList()
  },
  // destroyed() {
  //   this.formData0[0].formModel = data.basicForm0[0].formModel;
  //   this.$store.dispatch("device_pointcheck_plan/clearAll");
  // },
  methods: {
    // 上移、下移
    moveProTableData(from, to) {
      if (!this.productRuleForm || !this.productRuleForm.tableData) {
        return
      }

      const arr = this.productRuleForm.tableData
      // 检测移动边界
      if (to < 0 || to > arr.length - 1) {
        return
      }
      // 移动元素
      const moveTarget = arr.splice(from, 1)[0]
      arr.splice(to, 0, moveTarget)
      this.productRuleForm.tableData = arr
    },
    // 删除
    deleteProTableData(index) {
      if (!this.productRuleForm || !this.productRuleForm.tableData) {
        return
      }
      const arr = this.productRuleForm.tableData
      // 检测边界
      if (index < 0 || index > arr.length - 1) {
        return
      }
      arr.splice(index, 1)
      this.productRuleForm.tableData = arr
    },

    deleteDeviceData(index) {
      if (!this.tableData || this.tableData.length <= 0) {
        return
      }

      const arr = this.tableData
      // 检测边界
      if (index < 0 || index > arr.length - 1) {
        return
      }
      arr.splice(index, 1)
      this.tableData = arr
    },

    async getItemsList(args) {
      // this.listLoading = true
      console.log(args)
      await this.$store.dispatch(
        'device_pointcheck_items/requestDeviceList',
        args
      )
      this.paginationInfo2.total = this.$store.state.device_pointcheck_items.total
    },
    handleFilter2(args) {
      this.listQuery.page = 1
      this.getList(args)
    },
    async getDeviceList(args) {
      // this.listLoading = true
      console.log(args)
      await this.$store.dispatch('deviceBasic/requestDeviceList', args)
      this.paginationInfo.total = this.$store.state.deviceBasic.total
    },
    handleFilter(args) {
      this.listQuery.page = 1
      this.getDeviceList(args)
    },
    addCheckedDevice() {
      console.log('添加点位设备')
      this.dialogDeviceVisible = true
    },
    addCheckedItems() {
      console.log('添加点位项目')
      this.getGroupItemsList()
      this.dialogPartVisible = true
    },
    addCheckedNocontentItem() {
      // 添加空白点检项
      // this.tableData2s.push({id:this.tableData2s.length})
      this.productRuleForm.tableData.push({
        date: '',
        name: '',
        phone: '',
        address: ''
      })
    },
    handleSelectionChange(row) {
      console.log('选择点检设备', row)
      this.chooseDevices = row
    },
    handleSelectionItemsChange(row) {
      console.log('选择点检项目', row)
      this.chooseItems = row
    },
    addChooseDevices(row) {
      console.log(this.chooseDevices)
      this.tableData = this.chooseDevices
      // this.tableData=uniComplexArr(this.tableData)
      this.dialogDeviceVisible = false
    },
    addChooseItems(row) {
      console.log(this.chooseItems, '++++this.chooseItems+++++')
      //  this.productRuleForm.tableData = this.chooseItems;
      this.$set(this.productRuleForm, 'tableData', this.chooseItems)
      console.log(this.tableData2s)
      console.log(this.productRuleForm, '+++++this.productRuleForm+++++')

      this.dialogPartVisible = false
    },
    // 查询点检项分组
    getGroupItemsList() {
      this.$store.dispatch('device_pointcheck_itemsGroup/getItemsGroupList').then(res => {
        const { data } = res
        const itemGropusData = data.map(e => {
          return { label: e.groupName, value: e.itemGroupId }
        })
        this.$set(this.formOptions2s.forms[0], 'options', itemGropusData)
      })
    },
    cancel2s() {
      this.dialogPartVisible = false
    },
    cancel() {
      this.dialogDeviceVisible = false
    },
    // 提交数据
    submit(status) {
      this.$refs['productRuleForm'].validate(valid => {
        const items = {
          planRefDeviceList: this.chooseDevices.map(e => {
            e.useOrganId = e.organId
            e.useOrganName = e.organName
            return e
          }),
          planItemList: this.productRuleForm.tableData,
          subCode: status // 0存草稿 1提交审批
        }

        const data = Object.assign(
          {},

          this.formData0[0].formModel,
          this.operateForm0[0].formModel,
          items
        )

        data.userName = data.userId.split(',')[1]
        data.userId = data.userId.split(',')[0]
        if (data.regularTime && data.regularTime.length > 0) {
          data.regularStartTime =
            data.regularTime[0].slice(0, 10) + ' 00:00:00'
          data.regularEndTime = data.regularTime[1].slice(0, 10) + ' 23:59:59'
        }
        this.$store
          .dispatch('device_pointcheck_plan/saveDeviceInfo', data)
          .then(response => {
            this.$store.dispatch('tagsView/delVisitedView', {
              path: this.$route.fullPath
            })
            this.$router.push('/plant-check/plan')
          })
      })
    }
  }
}
</script>

<style lang="scss">
.checked-device {
  background: white;
  margin: 10px 0;
  padding: 20px;
  .checked-device-title {
    margin: 10px 0;
    font-size: 16px;
  }
}
.check-device-buttons {
  margin: 20px 0;
  text-align: center;
}
</style>
